package org.gongliang.common.web;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang3.StringEscapeUtils;
import org.gongliang.kit.str.StrKit;

/**
 * 
 * @description 与spring mvc的@InitBinder结合 用于防止XSS攻击
 * @author gongliang
 * @date 2015年3月29日 下午4:24:51
 */
public class StringEscapeEditor extends PropertyEditorSupport {

	private boolean escapeHTML;// 编码HTML
	private boolean escapeJavaScript;// 编码javascript
	private boolean escapeSQL; // sql注入

	public StringEscapeEditor() {
		super();
	}

	public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript, boolean escapeSQL) {
		super();
		this.escapeHTML = escapeHTML;
		this.escapeJavaScript = escapeJavaScript;
		this.escapeSQL = escapeSQL;
	}

	@Override
	public String getAsText() {
		Object value = getValue();
		return value != null ? value.toString() : null;
	}

	public static void main(String[] args) {
		System.out.println(StringEscapeUtils.escapeHtml4("菜单"));
		System.out.println(StringEscapeUtils.escapeEcmaScript("菜单"));
		System.out.println(StringEscapeUtils
				.escapeHtml4("<p class='ue_t'> <br/> </p> <p> <br/> </p>"));
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (text == null || "".equals(text.trim())) {
			setValue(null);
		} else {
			String value = text;
			if (escapeHTML) {
				value = StringEscapeUtils.escapeHtml4(value);
			}
			if (escapeJavaScript) {
				value = StringEscapeUtils.escapeEcmaScript(value);
			}
			if (escapeSQL) {
				value = StrKit.escapeSql(value);
			}
			setValue(value);
		}
	}
}
